package com.loobot.album.service.impl;

import com.github.pagehelper.PageHelper;
import com.loobot.album.config.ProjectProperties;
import com.loobot.album.dao.mapper.PictureMapper;
import com.loobot.album.dao.model.Picture;
import com.loobot.album.exception.AppException;
import com.loobot.album.net.ErrorCode;
import com.loobot.album.net.RestResult;
import com.loobot.album.net.param.request.GetPictures;
import com.loobot.album.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

/**
 * @author: Ike.Fan
 * @date: 2019/3/15.
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Autowired
    PictureMapper pictureMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    ProjectProperties projectProperties;
    @Value("${loobot.service.fileSystem}")
    private String fileServer;
    @Value("${loobot.service.token}")
    private String fileServerToken;
    @Value("${loobot.service.directory}")
    private String fileServerDir;

    @Override
    public List<Picture> getPictures(GetPictures getPictures) {
        PageHelper.startPage(getPictures.getPageNum(),getPictures.getPageSize());
        return pictureMapper.selectByAlbumId(getPictures.getAlbumId());
    }

    @Override
    public Picture addPic(String albumUuid, String userId, MultipartFile file) {
//临时文件
        File tmpFile = new File(projectProperties.getMomentPath()+file.getOriginalFilename());
        if (!tmpFile.getParentFile().exists()) {
            tmpFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(tmpFile);
        } catch (IOException e) {
            throw new AppException(ErrorCode.ADD_FAILED.getCode(), e.getLocalizedMessage());
        }

        //loobot 请求头，授权token
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("loobot_header", fileServerToken);

        FileSystemResource fileSystemResource = new FileSystemResource(tmpFile);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file",fileSystemResource);
        param.add("memberId", fileServerDir);//服务器上存储目录

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        Object rest = restTemplate.postForEntity(fileServer+"/api/open/uploadImage",httpEntity, RestResult.class).getBody().getData();
        if(rest ==null){
            new Thread(() -> tmpFile.delete()).start();
            return null;
        }
        Picture picture = new Picture();
        picture.setAlbumId(albumUuid);
        picture.setUserId(userId);
        picture.setCreateTime(Calendar.getInstance().getTime());
        picture.setPicUrl((String) rest);
        new Thread(() -> tmpFile.delete()).start();

        if(pictureMapper.insertSelective(picture)>0){
            return picture;
        }else{
            return null;
        }
    }

    @Override
    public int delete(long id) {
        return pictureMapper.deleteByPrimaryKey(id);
    }
}
